/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.library.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.library.common.base.ApiResult;
import com.library.entity.*;
import com.library.entity.dto.QueryResourceDto;
import com.library.entity.dto.SearchDto;
import com.library.entity.vo.ArticleCatalogVo;
import com.library.entity.vo.BookResourceVo;
import com.library.entity.vo.JournalSearchResultVo;
import com.library.mapper.ResourceMapper;
import com.library.service.*;
import com.library.util.Common1Util;
import com.library.util.MoJiCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源
 *
 * @author pig
 * @date 2023-10-31 14:34:33
 */
@Service
@Slf4j
public class ResourceServiceImpl extends ServiceImpl<ResourceMapper, ResourceEntity> implements ResourceService {

    @Autowired
    private BookDataTypeServiceImpl bookDataTypeService;
    @Autowired
    private BookCommentInfoService bookCommentInfoService;
    @Autowired
    private RUserLikeService rUserLikeService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserResourceService userResourceService;
    @Autowired
    private UserResourceBrowsingLogService userResourceBrowsingLogService;
    @Autowired
    private ResourceAuditService resourceAuditService;
    @Autowired
    private ResourceHomeService resourceHomeService;
    //@Value("${digitallibrary.httpIp}")
    private String httpIp;

    //@Value("${digitallibrary.username}")
    private String username;

    //Value("${digitallibrary.password}")
    private String password;
    //@Value("${digitallibrary.productId}")
    private String productId;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult saveAll() {
        try {
            String a;
            String b;
            String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
            ObjectMapper objectMapper = new ObjectMapper();
            BookExposureEntity bookExposureEntity = new BookExposureEntity();
            bookExposureEntity.setUsername("hndzyx");
            bookExposureEntity.setPassword("123456");
            bookExposureEntity.setProductId("1728954899846217729");
            String json = objectMapper.writeValueAsString(bookExposureEntity);
            String jsonString = bookDataTypeService.resourceType(token, "http://10.100.24.103:9999" + "/digitallibrary/bookExposure/getProductResources", json);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONArray dataArray = jsonObject.getJSONArray("data");

            ResourceEntity byId = this.getById(0);
            if (byId.getStatus().equals("0")) {
                a = "0";
                b = "1";
            } else {
                a = "1";
                b = "0";
            }
            byId.setStatus(b);
            this.updateById(byId);
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                ResourceEntity bookType = new ResourceEntity();
                String id = dataObject.getString("resourceId");
                bookType.setResourceId(Long.valueOf(id));
                if (dataObject.getString("dataTypeId") != null) {
                    String dataTypeId = dataObject.getString("dataTypeId");
                    bookType.setDataTypeId(Long.valueOf(dataTypeId));
                }
                if (dataObject.getString("bookTypeId") != null) {
                    String bookTypeId = dataObject.getString("bookTypeId");
                    bookType.setBookTypeId(Long.valueOf(bookTypeId));
                }
                if (dataObject.getString("author") != null) {
                    bookType.setAuthor(dataObject.getString("author"));
                }
                if (dataObject.getString("createTime") != null) {
                    String pattern = "yyyy-MM-dd HH:mm:ss";
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
                    String createTimeStr = dataObject.getString("createTime");
                    LocalDateTime createTime = LocalDateTime.parse(createTimeStr, formatter);
                    bookType.setCreateTime(createTime);
                }
                if (dataObject.getString("press") != null) {
                    bookType.setPress(dataObject.getString("press"));
                }
                if (dataObject.getString("briefIntroduction") != null) {
                    bookType.setBriefIntroduction(dataObject.getString("briefIntroduction"));
                }
                if (dataObject.getString("resourceName") != null) {
                    bookType.setResourceName(dataObject.getString("resourceName"));
                }
                bookType.setCover(dataObject.getString("coverPictureUrl"));
                bookType.setStatus(b);
                ResourceEntity existingEntity = this.getById(id);
                if (existingEntity != null) {
                    this.updateById(bookType);
                } else {
                    long pageView = 0;
                    bookType.setPageView(pageView);
                    bookType.setType(pageView);
                    this.save(bookType);
                }

            }
            LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ResourceEntity::getStatus, a);
            this.remove(wrapper);
            return ApiResult.ok("同步成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void pageView(Long resourceId) {
        ResourceEntity existingEntity = this.getById(resourceId);
        Long pageView = existingEntity.getPageView();
        existingEntity.setPageView(pageView + 1);
        this.updateById(existingEntity);
    }

    @Override
    public ApiResult getProductResourcesDetails(String resourceId) {
        try {
            String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
            ObjectMapper objectMapper = new ObjectMapper();
            BookExposureEntity bookExposureEntity = new BookExposureEntity();
            bookExposureEntity.setUsername("hndzyx");
            bookExposureEntity.setPassword("123456");
            bookExposureEntity.setProductId("1720251448509333505");
            bookExposureEntity.setResourceId(resourceId);
            String json = objectMapper.writeValueAsString(bookExposureEntity);
            String jsonString =
                    //"{\"code\":0,\"msg\":\"汉魏士人的思想历程详情\",\"data\":{\"id\":\"1724497002389471233\",\"bookName\":\"汉魏士人的思想历程\",\"author\":\"孙生 白笑天\",\"bookNumber\":\"978-7-227-04912-8\",\"briefIntroduction\":null,\"press\":\"宁夏人民出版社\",\"publicationTime\":\"2011-12-01\",\"bookClassification\":\"社会科学总论\",\"dataTypeId\":\"1719628518976913409\",\"bookDataType\":\"电子书\",\"bookGradeType\":\"B\",\"labelType\":null,\"copyrightOwner\":\"北京九州文心\",\"file\":[{\"fileName\":\"汉魏士人的思想历程\",\"size\":3.0,\"resourceName\":\"汉魏士人的思想历程\",\"fileUrl\":\"https://zhongtai.zhongjiaoyuntu.com:9002/dzyx/20240428/黄老师上传1宁夏吉林/汉魏士人的思想历程/汉魏士人的思想历程.pdf\",\"type\":\"pdf\"}],\"coverPictures\":[{\"coverPictureName\":\"汉魏士人的思想历程\",\"coverPictureUrl\":\"https://zhongtai.zhongjiaoyuntu.com:9002/dzyx/20240428/黄老师上传1宁夏吉林/汉魏士人的思想历程/汉魏士人的思想历程.jpg\",\"type\":\"jpg\"}]}}\n";
                    bookDataTypeService.resourceType(token, "http://10.100.24.103:9999" + "/digitallibrary/bookExposure/getProductResourcesDetails", json);
            log.info("资源返回报文=============={}",jsonString);

            JSONObject jsonObject = JSON.parseObject(jsonString);
            ResourceEntity byId = this.getById(resourceId);
            Long pageView = byId.getPageView();
            byId.setPageView(pageView + 1);
            this.updateById(byId);
//            log.info("getProductResourcesDetails:{}",jsonObject);
//            log.info("byId:{}",byId);
//            log.info("resourceId:{}",resourceId);
//            log.info("json:{}",json);
//            log.info("jsonString:{}",jsonString);
//            log.info("httpIp:{}",httpIp);
//            log.info("token:{}",token);
//            log.info("username:{}",username);
//            log.info("password:{}",password);
//            log.info("productId:{}",productId);
//            if(ObjectUtil.isEmpty(jsonObject)){
//                jsonObject=new JSONObject();
//            }
            jsonObject.put("pageView", byId.getPageView());
            System.out.println(jsonObject);

            return ApiResult.ok(jsonObject);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public ApiResult search(SearchDto dto) {
        List<Map> lists = new ArrayList<>();
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.like(ResourceEntity::getResourceName, dto.getSearch());
        List<ResourceEntity> list = this.list(wrapper);

        Map<Long, List<ResourceEntity>> groupedMap = list.stream()
                .collect(Collectors.groupingBy(ResourceEntity::getDataTypeId));

        for (BookDataTypeEntity bookDataTypeEntity : bookDataTypeService.list()) {
            Map map = new HashMap();
            List<ResourceEntity> dataTypeId1List = groupedMap.get(bookDataTypeEntity.getId());
            map.put("dataTypeId", bookDataTypeEntity.getId());
            map.put("dataType", bookDataTypeEntity.getDataType());
            map.put("resource", dataTypeId1List);
            lists.add(map);
        }

        return ApiResult.ok(lists);
    }

    @Override
    public ApiResult books(Long id) {
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getDataTypeId, id);
        wrapper.isNotNull(ResourceEntity::getBriefIntroduction);
        wrapper.orderByDesc(ResourceEntity::getType);
        wrapper.last("LIMIT 5");
        List<ResourceEntity> resourceEntities = this.list(wrapper);
        map.put("book", resourceEntities);

        LambdaQueryWrapper<ResourceEntity> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(ResourceEntity::getDataTypeId, id);
        wrapper1.orderByDesc(ResourceEntity::getPageView);
        wrapper1.last("LIMIT 10");
        List<ResourceEntity> resourceEntitie = this.list(wrapper1);
        map.put("bookTop", resourceEntitie);

        list.add(map);
        return ApiResult.ok(list);
    }

    @Override
    public ApiResult video(Long id) {
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getDataTypeId, id);
        wrapper.isNotNull(ResourceEntity::getBriefIntroduction);
        wrapper.orderByDesc(ResourceEntity::getType);
        wrapper.last("LIMIT 5");
        List<ResourceEntity> resourceEntities = this.list(wrapper);
        map.put("video", resourceEntities);

        LambdaQueryWrapper<ResourceEntity> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(ResourceEntity::getDataTypeId, id);
        wrapper1.orderByDesc(ResourceEntity::getPageView);
        wrapper1.last("LIMIT 10");
        List<ResourceEntity> resourceEntitie = this.list(wrapper1);
        map.put("videoTap", resourceEntitie);

        list.add(map);
        return ApiResult.ok(list);
    }


    @Override
    public ApiResult periodical(Long id) {
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getDataTypeId, id);
        wrapper.orderByDesc(ResourceEntity::getType);
        long totalCount = 28;

        int pageSize = 14;

        long totalPages = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;

        List<List<ResourceEntity>> lists = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            // 分页查询
            List<ResourceEntity> pageList = this.page(new Page<>(i, pageSize), wrapper).getRecords();
            // 将当前页的数据放到子列表中
            List<List<ResourceEntity>> subLists = splitList(pageList, pageSize);
            // 将子列表加入到结果列表中
            lists.addAll(subLists);
        }
        return ApiResult.ok(lists);
    }

    @Override
    public ApiResult particularsBooks(String bookId) {
        List<ResourceEntity> list = new ArrayList<>();
        boolean containsSeparator = bookId.contains(",") || bookId.contains("，");
        if (containsSeparator) {
            String[] ids = bookId.split("[,，]");
            for (String id : ids) {
                ResourceEntity byId = this.getById(id);
                if (byId == null) {
                    byId = new ResourceEntity();
                    byId.setResourceName("查无此图书");
                }
                list.add(byId);
            }
        } else {
            ResourceEntity byId = this.getById(bookId);
            if (byId == null) {
                byId = new ResourceEntity();
                byId.setResourceName("查无此图书");
            }
            list.add(byId);
        }

        return ApiResult.ok(list);
    }



    @Override
    public ApiResult getJournalSearchResult(String searchKeywords,String openId) {
        try {
            String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
            ObjectMapper objectMapper = new ObjectMapper();
            JournalSearchResultVo journalSearchResultVo = new JournalSearchResultVo();
            journalSearchResultVo.setSearchKeywords(searchKeywords);
            journalSearchResultVo.setSort("2");
            journalSearchResultVo.setIdentifier("J");
            String json = objectMapper.writeValueAsString(journalSearchResultVo);
            String jsonString = bookDataTypeService.resourceType(token, "http://10.100.24.103:9999" + "/digitallibrary/journal/getJournalSearchResult", json);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            JSONArray resultsArray = dataObject.getJSONArray("results");
            for (int i = 0; i < resultsArray.size(); i++) {
                JSONObject result = resultsArray.getJSONObject(i);
                String journalname = result.getString("journalname");
                if (journalname.equals(searchKeywords)){
                    log.info("资源id========={}",result.get("id"));
                    String recommendValue="";
                    String totalReadCount="";
                    String completeReadCount="";
                    String commentCount="";
                    int recommendCount=0;
                    int commonCount=0;
                    int badCount=0;
                    String collectCount="";
                    String sfRead="";

                    Object id = result.get("id");
                    LambdaQueryWrapper<ResourceEntity> wrapperRescource=new LambdaQueryWrapper<>();
                    wrapperRescource.eq(ResourceEntity::getDataTypeId,1719628593258037250L);
                    wrapperRescource.eq(ResourceEntity::getResourceName,searchKeywords);
                    wrapperRescource.eq(ResourceEntity::getStatus,"0");
                    List<ResourceEntity> list = this.list(wrapperRescource);
                    if (list != null&&list.size()>0) {
                        result.put("id",list.get(0).getResourceId()+"");
                    }
                    else{
                        return ApiResult.failed("找不到当前期刊资源");
                    }
                    BookCommentInfo bookCommentInfo =bookCommentInfoService.getOne(
                            new LambdaQueryWrapper<BookCommentInfo>()
                                    .eq(BookCommentInfo::getBookCode,result.get("id")));
                    if(bookCommentInfo !=null){
                        recommendValue=bookCommentInfo.getRecommendValue()+"";
                        totalReadCount=bookCommentInfo.getTotalReadCount()+"";
                        completeReadCount=bookCommentInfo.getCompleteReadCount()+"";
                        commentCount=bookCommentInfo.getCommentCount()+"";
                        recommendCount=ObjectUtil.isEmpty(bookCommentInfo.getRecommendCount())?0:bookCommentInfo.getRecommendCount();
                        commonCount=ObjectUtil.isEmpty(bookCommentInfo.getCommonCount())?0:bookCommentInfo.getCommonCount();
                        badCount=ObjectUtil.isEmpty(bookCommentInfo.getBadCount())?0:bookCommentInfo.getBadCount();
                        collectCount=bookCommentInfo.getCollectCount()+"";
                        sfRead=bookCommentInfo.getSfRead()+"";
                    }
                    result.put("recommendValue", recommendValue);
                    result.put("totalReadCount", totalReadCount);
                    result.put("completeReadCount", completeReadCount);
                    result.put("commentCount", commentCount);
                    result.put("recommendCount", recommendCount);
                    result.put("commonCount", commonCount);
                    result.put("badCount", badCount);
                    result.put("collectCount", collectCount);
                    result.put("sfRead", sfRead);
                    if(ObjectUtil.isNotEmpty(openId)){
                        LambdaQueryWrapper<RUserLike> wrapper0=new LambdaQueryWrapper<>();
                        wrapper0.eq(RUserLike::getType,2);
                        wrapper0.eq(RUserLike::getUserId,openId);
                        wrapper0.eq(RUserLike::getResourceId,result.get("id"));
                        RUserLike rUserLike=rUserLikeService.getOne(wrapper0);
                        if(rUserLike !=null){
                            result.put("sfComment", 1);
                            result.put("commentType", rUserLike.getCommentType());
                        }
                    }
                    UserResource userResource =new UserResource();
                    userResource.setOpenId(openId);
                    //userResource.setResourceId(Long.valueOf(id+""));
                    userResource.setResourceId(Long.valueOf(result.get("id")+""));
                    userResourceService.add(userResource);
                    UserResourceBrowsingLog log=new UserResourceBrowsingLog();
                    log.setOpenId(openId);
                    log.setResourceId(Long.valueOf(result.get("id")+""));
                    log.setReferrerUrl("app");
                    log.setCreatedAt(new Date());
                    LambdaQueryWrapper<UserInfo> wrapper=new LambdaQueryWrapper<>();
                    wrapper.eq(UserInfo::getOpenId,openId);
                    UserInfo userInfo=userInfoService.getOne(wrapper);
                    if(userInfo !=null){
                        log.setProvince("41");
                        log.setCity(userInfo.getCityCode());
                        log.setArea(userInfo.getAreaCode());
                    }
                    userResourceBrowsingLogService.save(log);
                    return ApiResult.ok(result);
                }
            }
            log.info("jsonObject: " + jsonObject);
            return ApiResult.failed("找不到当前期刊资源");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ApiResult getArticleCatalog(ArticleCatalogVo articleCatalogVo) {
        try {
            String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(articleCatalogVo);
            String jsonString = bookDataTypeService.resourceType(token, "http://10.100.24.103:9999" + "/digitallibrary/journal/getArticleCatalog", json);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            return ApiResult.ok(jsonObject);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ApiResult getArticleDetail(String id) {
        try {
            String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
            String jsonString = bookDataTypeService.get(token, "http://10.100.24.103:9999" + "/digitallibrary/journal/getArticleDetail/" + id);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            return ApiResult.ok(jsonObject);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ApiResult audio(Long id) {
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        LambdaQueryWrapper<ResourceEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ResourceEntity::getDataTypeId, id);
        wrapper.isNotNull(ResourceEntity::getBriefIntroduction);
        wrapper.orderByDesc(ResourceEntity::getType);
        wrapper.last("LIMIT 5");
        List<ResourceEntity> resourceEntities = this.list(wrapper);
        map.put("audio", resourceEntities);

        LambdaQueryWrapper<ResourceEntity> wrapper1 = Wrappers.lambdaQuery();
        wrapper1.eq(ResourceEntity::getDataTypeId, id);

        wrapper1.last("LIMIT 10");
        List<ResourceEntity> resourceEntitie = this.list(wrapper1);
        map.put("audioTop", resourceEntitie);

        list.add(map);
        return ApiResult.ok(list);
    }

    @Override
    public ApiResult pageList(IPage page, LambdaQueryWrapper<ResourceEntity> wrapper) {

        IPage<ResourceEntity> paged = this.page(page, wrapper);

        List<ResourceEntity> records = paged.getRecords();
        for (ResourceEntity record : records) {
            BookDataTypeEntity byId = bookDataTypeService.getById(record.getDataTypeId());
            record.setStatus(byId.getDataType());
        }
        return ApiResult.ok(paged);
    }

    @Override
    public JSONObject detail(QueryResourceDto dto) {
        LambdaQueryWrapper<ResourceEntity> wrapperResource = Wrappers.lambdaQuery();
        wrapperResource.eq(ResourceEntity::getResourceId, dto.getId());
        ResourceEntity one = this.getOne(wrapperResource);
        //更新首页资源浏览量
        LambdaQueryWrapper<ResourceHome> resourceHomeLambdaQueryWrapper = Wrappers.lambdaQuery();
        resourceHomeLambdaQueryWrapper.eq(ResourceHome::getResourceId, dto.getId());
        if (resourceHomeService.getOne(resourceHomeLambdaQueryWrapper) != null) {
            ResourceHome one1 = resourceHomeService.getOne(resourceHomeLambdaQueryWrapper);
            Long pageView = one1.getPageView();
            one1.setPageView(pageView + 1);
            resourceHomeService.updateById(one1);
        }

        if (one != null) {
            if("app".equals(one.getSource()))
            {
                String jsonString ="{\"code\":\"1\",\"msg\":\"成功\"}";
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if(jsonObject.get("data") ==null){
                    jsonObject.put("msg",one.getResourceName()+"详情");
                    JSONObject jsonObject1=new JSONObject();
                    jsonObject1.put("copyrightOwner","");
                    jsonObject1.put("author",one.getAuthor());
                    jsonObject1.put("dataTypeld",one.getDataTypeId());
                    jsonObject1.put("labelType","");
                    jsonObject1.put("bookClassification","");
                    jsonObject1.put("brieflntroduction",one.getResourceName());
                    jsonObject1.put("bookGradeType","");
                    jsonObject1.put("bookName",one.getResourceName());
                    jsonObject1.put("publicationTime","");
                    jsonObject1.put("id",one.getResourceId());
                    JSONArray jonArray=new JSONArray();
                    JSONObject object1=new JSONObject();
                    object1.put("coverPictureName",one.getResourceName());
                    object1.put("coverPictureUrl",one.getCover());
                    object1.put("type","jpg");
                    jonArray.add(object1);
                    jsonObject1.put("coverPictures",jonArray);

                    Long resourceAuditId = one.getResourceAuditId();
                    ResourceAudit byId = resourceAuditService.getById(resourceAuditId);
                    String resourceFile = byId.getResourceFile();
                    int lastIndex = resourceFile.lastIndexOf('.');
                    String substring = resourceFile.substring(lastIndex + 1);

                    JSONArray jonArray1=new JSONArray();
                    JSONObject object2=new JSONObject();
                    object2.put("resourceName",one.getResourceName());
                    object2.put("fileName",one.getResourceName());
                    object2.put("fileUrl",resourceFile);
                    object2.put("type",substring);
                    jonArray1.add(object2);
                    jsonObject1.put("file",jonArray1);
                    jsonObject.put("data",jsonObject1);
                }
                return jsonObject;
            }else{
                try {
                    String token = bookDataTypeService.selectToken("http://10.100.24.103:9999" + "/auth/oauth2/token");
                    ObjectMapper objectMapper = new ObjectMapper();
                    BookExposureEntity bookExposureEntity = new BookExposureEntity();
                    bookExposureEntity.setUsername("hndzyx");
                    bookExposureEntity.setPassword("123456");
                    bookExposureEntity.setProductId("1720251448509333505");
                    bookExposureEntity.setResourceId(dto.getId());
                    String json = objectMapper.writeValueAsString(bookExposureEntity);
                    String jsonString =
                            //"{\"code\":0,\"msg\":\"汉魏士人的思想历程详情\",\"data\":{\"id\":\"1724497002389471233\",\"bookName\":\"汉魏士人的思想历程\",\"author\":\"孙生 白笑天\",\"bookNumber\":\"978-7-227-04912-8\",\"briefIntroduction\":null,\"press\":\"宁夏人民出版社\",\"publicationTime\":\"2011-12-01\",\"bookClassification\":\"社会科学总论\",\"dataTypeId\":\"1719628518976913409\",\"bookDataType\":\"电子书\",\"bookGradeType\":\"B\",\"labelType\":null,\"copyrightOwner\":\"北京九州文心\",\"file\":[{\"fileName\":\"汉魏士人的思想历程\",\"size\":3.0,\"resourceName\":\"汉魏士人的思想历程\",\"fileUrl\":\"https://zhongtai.zhongjiaoyuntu.com:9002/dzyx/20240428/黄老师上传1宁夏吉林/汉魏士人的思想历程/汉魏士人的思想历程.pdf\",\"type\":\"pdf\"}],\"coverPictures\":[{\"coverPictureName\":\"汉魏士人的思想历程\",\"coverPictureUrl\":\"https://zhongtai.zhongjiaoyuntu.com:9002/dzyx/20240428/黄老师上传1宁夏吉林/汉魏士人的思想历程/汉魏士人的思想历程.jpg\",\"type\":\"jpg\"}]}}\n";
                            bookDataTypeService.resourceType(token, "http://10.100.24.103:9999" + "/digitallibrary/bookExposure/getProductResourcesDetails", json);
                    log.info("资源返回报文=============={}",jsonString);

                    JSONObject jsonObject = JSON.parseObject(jsonString);
                    ResourceEntity byId = this.getById(Long.parseLong(dto.getId()));
                    if(byId==null){
                        throw new RuntimeException("资源不存在,请核查!");
                    }
//                    if(jsonObject.get("data") ==null){
//                        jsonObject.put("msg",byId.getResourceName()+"详情");
//                        JSONObject jsonObject1=new JSONObject();
//                        jsonObject1.put("copyrightOwner","");
//                        jsonObject1.put("author",byId.getAuthor());
//                        jsonObject1.put("dataTypeld",byId.getDataTypeId());
//                        jsonObject1.put("labelType","");
//                        jsonObject1.put("bookClassification","");
//                        jsonObject1.put("brieflntroduction",byId.getResourceName());
//                        jsonObject1.put("bookGradeType","");
//                        jsonObject1.put("bookName",byId.getResourceName());
//                        jsonObject1.put("publicationTime","");
//                        jsonObject1.put("id",byId.getResourceId());
//                        JSONArray jonArray=new JSONArray();
//                        JSONObject object1=new JSONObject();
//                        object1.put("coverPictureName",byId.getResourceName());
//                        object1.put("coverPictureUrl",byId.getCover());
//                        object1.put("type","jpg");
//                        jonArray.add(object1);
//                        JSONObject object2=new JSONObject();
//                        object2.put("coverPictureName",byId.getResourceName());
//                        object2.put("coverPictureUrl",byId.getCover());
//                        object2.put("type",null);
//                        jonArray.add(object2);
//                        jsonObject1.put("coverPictures",jonArray);
//                        JSONArray jonArray1=new JSONArray();
//                        jsonObject1.put("file",jonArray1);
//                        jsonObject.put("data",jsonObject1);
//                    }
                    Long pageView = byId.getPageView();
                    byId.setPageView(pageView + 1);
                    this.updateById(byId);
                    jsonObject.put("pageView", byId.getPageView());
                    System.out.println(jsonObject);
                    String recommendValue="";
                    String totalReadCount="";
                    String completeReadCount="";
                    String commentCount="";
                    int recommendCount=0;
                    int commonCount=0;
                    int badCount=0;
                    String collectCount="";
                    String sfRead="";
                    BookCommentInfo bookCommentInfo =bookCommentInfoService.getOne(
                            new LambdaQueryWrapper<BookCommentInfo>()
                                    .eq(BookCommentInfo::getBookCode,byId.getResourceId()+""));
                    if(bookCommentInfo !=null){
                        recommendValue=bookCommentInfo.getRecommendValue()+"";
                        totalReadCount=bookCommentInfo.getTotalReadCount()+"";
                        completeReadCount=bookCommentInfo.getCompleteReadCount()+"";
                        commentCount=bookCommentInfo.getCommentCount()+"";
                        recommendCount=ObjectUtil.isEmpty(bookCommentInfo.getRecommendCount())?0:bookCommentInfo.getRecommendCount();
                        commonCount=ObjectUtil.isEmpty(bookCommentInfo.getCommonCount())?0:bookCommentInfo.getCommonCount();
                        badCount=ObjectUtil.isEmpty(bookCommentInfo.getBadCount())?0:bookCommentInfo.getBadCount();
                        collectCount=bookCommentInfo.getCollectCount()+"";
                        sfRead=bookCommentInfo.getSfRead()+"";
                    }
                    jsonObject.put("recommendValue", recommendValue);
                    jsonObject.put("totalReadCount", totalReadCount);
                    jsonObject.put("completeReadCount", completeReadCount);
                    jsonObject.put("commentCount", commentCount);
                    jsonObject.put("recommendCount", recommendCount);
                    jsonObject.put("commonCount", commonCount);
                    jsonObject.put("badCount", badCount);
                    jsonObject.put("collectCount", collectCount);
                    jsonObject.put("sfRead", sfRead);
                    if(ObjectUtil.isNotEmpty(dto.getOpenId())){
                        LambdaQueryWrapper<RUserLike> wrapper0=new LambdaQueryWrapper<>();
                        wrapper0.eq(RUserLike::getType,2);
                        wrapper0.eq(RUserLike::getUserId,dto.getOpenId());
                        wrapper0.eq(RUserLike::getResourceId,byId.getResourceId());
                        RUserLike rUserLike=rUserLikeService.getOne(wrapper0);
                        if(rUserLike !=null){
                            jsonObject.put("sfComment", 1);
                            jsonObject.put("commentType", rUserLike.getCommentType());
                        }
                    }
                    UserResource userResource =new UserResource();
                    userResource.setOpenId(dto.getOpenId());
                    userResource.setResourceId(Long.valueOf(dto.getId()));
                    userResourceService.add(userResource);
                    UserResourceBrowsingLog log=new UserResourceBrowsingLog();
                    log.setOpenId(dto.getOpenId());
                    log.setResourceId(Long.valueOf(dto.getId()));
                    log.setReferrerUrl("app");
                    log.setCreatedAt(new Date());
                    LambdaQueryWrapper<UserInfo> wrapper=new LambdaQueryWrapper<>();
                    wrapper.eq(UserInfo::getOpenId,dto.getOpenId());
                    UserInfo userInfo=userInfoService.getOne(wrapper);
                    if(userInfo !=null){
                        log.setProvince("41");
                        log.setCity(userInfo.getCityCode());
                        log.setArea(userInfo.getAreaCode());
                        log.setCommittee(userInfo.getCommitteeCode());
                        log.setStreet(userInfo.getStreetCode());
                    }
                    userResourceBrowsingLogService.save(log);
                    return jsonObject;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }else{
            //找不到资源
            throw new RuntimeException("资源不存在,请核查!");
        }
    }

    @Override
    public boolean like(Long id,String openId) {
        ResourceEntity pbResource=this.getById(id);
        if(pbResource==null){
            throw new RuntimeException("资源不存在,请核查!");
        }
        int count=pbResource.getLikeCount();
        if(ObjectUtil.isNotEmpty(count)){
            pbResource.setLikeCount(count+1);
        }else{
            pbResource.setLikeCount(1);
        }

        if (resourceHomeService.getById(id) != null) {
            ResourceHome byId = resourceHomeService.getById(id);
            int count1=byId.getLikeCount();
            if(ObjectUtil.isNotEmpty(count1)){
                byId.setLikeCount(count1+1);
            }else{
                byId.setLikeCount(1);
            }
            resourceHomeService.updateById(byId);
        }

        UserInfo userInfo=userInfoService.getUserByOpenId(openId);
        if(userInfo==null){
            throw new RuntimeException("用户不存在,请核查!");
        }

        //插入用户点赞关联表
        RUserLike userLike=rUserLikeService.getOne(new LambdaQueryWrapper<RUserLike>()
                .eq(RUserLike::getResourceId,pbResource.getResourceId()+"")
                .eq(RUserLike::getType,1)
                .eq(RUserLike::getUserId,userInfo.getId()+""));
        if(userLike==null){
            RUserLike rUserLike=new RUserLike();

            rUserLike.setUserId(userInfo.getId()+"");
            rUserLike.setResourceId(pbResource.getResourceId()+"");
            rUserLike.setType(1);
            rUserLike.setCreateTime(new Date());
            rUserLikeService.save(rUserLike);
        }

        return this.updateById(pbResource);
    }

    @Override
    public boolean cancelLike(Long id,String openId) {
        ResourceEntity pbResource=this.getById(id);
        if(pbResource==null){
            throw new RuntimeException("资源不存在,请核查!");
        }
        UserInfo userInfo=userInfoService.getUserByOpenId(openId);
        if(userInfo==null){
            throw new RuntimeException("用户不存在,请核查!");
        }
        int count=pbResource.getLikeCount();
        if(ObjectUtil.isNotEmpty(count) && count>0){
            pbResource.setLikeCount(count-1);
        }
        rUserLikeService.remove(new LambdaQueryWrapper<RUserLike>()
        .eq(RUserLike::getResourceId,pbResource.getResourceId()+"")
        .eq(RUserLike::getUserId,userInfo.getId()+""));
        return this.updateById(pbResource);
    }

    private <T> List<List<T>> splitList(List<T> list, int pageSize) {
        List<List<T>> result = new ArrayList<>();
        int count = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
        for (int i = 0; i < count; i++) {
            int start = i * pageSize;
            int end = Math.min((i + 1) * pageSize, list.size());
            result.add(list.subList(start, end));
        }
        return result;
    }
}

